package com.qmyx.supplychain.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.supplychain.common.configuration.LINKPlatformConfig;
import com.ytjj.qmyx.supplychain.common.configuration.LinkConfigObject;
import com.ytjj.qmyx.supplychain.common.enums.AbroadOrderPushTypeEnum;
import com.ytjj.qmyx.supplychain.common.model.dto.AbroadOrderDto;
import com.ytjj.qmyx.supplychain.common.model.dto.AbroadReturnOrderDto;
import com.ytjj.qmyx.supplychain.common.model.response.LinkErpResponse;
import com.ytjj.qmyx.supplychain.common.model.response.NewBankerOrderResponse;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.YxAbroadOrderRecord;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerOrder;
import com.ytjj.qmyx.supplychain.mapper.entity.YxExpressOrders;
import com.ytjj.qmyx.supplychain.mapper.entity.YxOrders;
import com.ytjj.qmyx.supplychain.service.LinkErpService;
import com.ytjj.qmyx.supplychain.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
@RefreshScope
public class OrderTask {
    /**
     * 包含境外商品的供应商id
     */
    @Value("${abroad.order.bankers:}")
    private String abroadBankerIds;
    /**
     * 境外商品上传wms系统的供应商id
     */
    @Value("${abroad.wms.bankerIds:}")
    private String abroadWMSBankerIds;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private AbroadOrderRecordMapper abroadOrderRecordMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private LinkErpService linkErpService;
    @Resource
    private LINKPlatformConfig linkPlatformConfig;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private ReissueLogisticsMapper reissueLogisticsMapper;

    /**
     * 推送境外订单-新增
     */
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void abroadOrderAdd() {
        log.info("===abroadOrderAdd start===");
        if (StringUtils.isEmpty(abroadBankerIds)) {
            log.info("===abroadBankerIds is null===");
            return;
        }
        try {
            List<String> idsStr = Arrays.asList(abroadBankerIds.split(","));
            List<Integer> ids = idsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
            List<AbroadOrderDto> list = ordersMapper.selectOrderInfoByBankerId(ids);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            //wms平台供应商id
            List<String> wmsBankerIdsStr = Arrays.asList(abroadWMSBankerIds.split(","));
            List<Integer> wmsBankerIds = wmsBankerIdsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(wmsBankerIds)) {
                log.info("===abroadWMSBankerIds is null===");
            }
            //link平台供应商id
            List<Integer> linkBankerIds =
                    linkPlatformConfig.getLinks().stream().map(LinkConfigObject::getBankerId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(linkBankerIds)) {
                log.info("===linkPlatformConfig.bankerIds is null===");
            }

            //查询平台配置的菜鸟erp供应商
            List<Integer> bankerIds = bankerMapper.selectByErpId(1);
            if (!CollectionUtils.isEmpty(bankerIds)){
                linkBankerIds.addAll(bankerIds);
            }
            log.info("================linkBankerIds : {}===============", bankerIds);
            //获取供应商erp配置
            List<LinkErpResponse> linkErpResponseList = linkErpService.getByBankIds(linkBankerIds);

            list.stream().forEach(item -> {
                if (null == item.getProductSum()) {
                    item.setProductSum(1);
                }
                if (!CollectionUtils.isEmpty(wmsBankerIds) && wmsBankerIds.contains(item.getBankerId())) {
                    //wms系统
                    orderService.handleToWMS(item);
                }
                LinkConfigObject linkConfigObject = new LinkConfigObject();
                if (!CollectionUtils.isEmpty(linkBankerIds) && linkBankerIds.contains(item.getBankerId())) {
                    List<LinkConfigObject> matchList = linkPlatformConfig.getLinks().stream()
                            .filter(link -> link.getBankerId().equals(item.getBankerId())).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(matchList)) {
                        log.error("===nocas中数据匹配异常= 没有该供应商的配置=={}", item.getBankerId());
                        if (!CollectionUtils.isEmpty(linkErpResponseList)){
                            //从后台中获取到的配置中找
                            List<LinkErpResponse> collect = linkErpResponseList.stream().filter(linkErpResponse -> item.getBankerId().equals(linkErpResponse.getBankerId())).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(collect)){
                                BeanUtils.copyProperties(collect.get(0),linkConfigObject);
                            }
                        }
                    }else {
                        linkConfigObject = matchList.get(0);
                    }
                    log.info("================linkConfigObject : {}===============", JSONObject.toJSONString(linkConfigObject));
                    if (StringUtils.isEmpty(linkConfigObject.getSecretKey())){
                        return;
                    }
                    log.info("===linkConfigObject={}", linkConfigObject.toString());
                    item.setExternalShopName(linkConfigObject.getExternalShopName());
                    item.setOwnerUserId(linkConfigObject.getOwnerUserId());
                    item.setCode(linkConfigObject.getCode());
                    item.setSecretKey(linkConfigObject.getSecretKey());
                    item.setBusinessUnitId(linkConfigObject.getBuId());
                    item.setStoreCode(linkConfigObject.getStoreCode());
                    item.setOrderSource(linkConfigObject.getOrderSource());
                    //link系统
                    orderService.handleToLINK(item);
                }
                //if(其它系统)
                // do something
            });
            list = null;
        } catch (Exception e) {
            log.error("===OrderTask.abroadOrderAdd is error==={}", e);
        }
        log.info("===abroadOrderAdd end===");
    }

    /**
     * 推送境外售后订单
     */
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void returnAbroadOrderPush() {
        log.info("===returnAbroadOrderPush start===");
        if (StringUtils.isEmpty(abroadBankerIds)) {
            log.info("===abroadBankerIds is null===");
            return;
        }
        try {
            List<String> idsStr = Arrays.asList(abroadBankerIds.split(","));
            List<Integer> bankerIds = idsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
            /**
             * 查询一小时前的退款订单
             */
            List<AbroadReturnOrderDto> abroadReturnOrderDtos = ordersMapper.selectReturnAbroadOrderList(bankerIds);
            if (CollectionUtils.isEmpty(abroadReturnOrderDtos)) {
                log.info("===returnAbroadOrderPush no data===");
                return;
            }
            List<String> wmsBankerIdsStr = Arrays.asList(abroadWMSBankerIds.split(","));
            List<Integer> wmsBankerIds = wmsBankerIdsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(wmsBankerIds)) {
                log.info("===abroadWMSBankerIds is null===");
                return;
            }
            abroadReturnOrderDtos.stream().forEach(item -> {
                /**
                 * 1.是否是需要上传wms的订单
                 * 2.是否已发送过wms系统
                 */
                if (wmsBankerIds.contains(item.getBankerId()) && !checkSendFlag(item.getChildOrderNo(), AbroadOrderPushTypeEnum.RETURN.getCode())) {
                    orderService.handleToWMSByReturnGoods(item.getChildOrderNo(), item.getReturnReason(), item.getBankerId(), item.getUserRemarks());
                }
                //if(其它系统)
                // do something
            });
        } catch (Exception e) {
            log.error("===推送境外售后订单异常：{}", e);
        }
        log.info("===returnAbroadOrderPush end===");
    }

    /**
     * 检查发送记录
     * @param childOrderNo
     * @param pushType
     * @return
     */
    private boolean checkSendFlag(String childOrderNo, Integer pushType) {
        Example haveExample = new Example(YxAbroadOrderRecord.class);
        haveExample.createCriteria().andEqualTo("orderNo", childOrderNo)
                .andEqualTo("type", pushType);
        int count = abroadOrderRecordMapper.selectCountByExample(haveExample);
        if (count > 0) {
            log.info("===订单编号：{}已上传过wms系统===", childOrderNo);
            return true;
        }
        return false;
    }

    /**
     * 境外订单清单回执查询
     */
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void abroadOrderReceipt() {
        orderService.selectAbroadOrderReceipt();
    }

    /**
     * 每晚凌晨检查前天完成的和关闭的订单，并发送到kafka
     */
//    @Scheduled(cron = "0 0 0 * * ?")
    public void checkOrderToKafkaRecord(){
        log.info("===checkOrderToKafkaRecord start===");
        orderService.checkOrderToKafkaRecord();
        log.info("===checkOrderToKafkaRecord end===");
    }

    /**
     * 快递签收后7天，更新订单状态为已完成
     * 发货快递和补单快递都要处理，因为很多包裹寄回了，重新补发了
     */
    @Scheduled(cron = "0 0 0/5 * * ?")
    public void updateOrderToFinished(){
        log.info("====开始处理签收7天的订单====");
        //发货物流订单
        List<YxOrders> yxOrders = ordersMapper.selectUnFinishOrdersBetweenTime(7);
        //补单物流订单
        List<YxOrders> replacementOrders = reissueLogisticsMapper.getOrderByReplacementCheck(7);
        if(!CollectionUtils.isEmpty(replacementOrders)){
            yxOrders.addAll(replacementOrders);
        }
        List<YxOrders> nowOrders = yxOrders.parallelStream().distinct().collect(Collectors.toList());
        log.info("====当前需要修改成【已完成】状态的发货订单有：{},补单订单有：{}====",yxOrders.size(),replacementOrders.size());
        if(CollectionUtils.isEmpty(nowOrders)){
            return;
        }
        for (YxOrders yxOrder : nowOrders) {
            orderService.updateOrderFinished(yxOrder);
        }
    }

    /**
     * 补偿售后订单，订单状态还是待发货状态的订单
     * 每隔5分执行一次
     */
//    @Scheduled(cron = "0 */5 * * * ?")
    public void updateReturnOrdersStatus(){
        log.info("====开始处理60天售后内售后单订单状态不是售后中的订单====");
        List<String> childOrderNoList = ordersMapper.queryReturnOrderBetweenTime(60);
        log.info("====当前需要修改成【售后单】状态的订单有："+childOrderNoList.size()+"单！====");
        if(CollectionUtils.isEmpty(childOrderNoList)){
            return;
        }
        orderService.updateOrderReturnGoodStatus(childOrderNoList);
    }
}
